<template>
  <div>
    <nav-menu :searchInfo.sync="searchInfo"></nav-menu>
    <div class="lg-container">
      <div class="main-container resource-container">
        <div class="resources">
          <div>
            <div id="app">
              <el-row class="tac">
                <el-col :span="5">
                  <h5>默认颜色</h5>
                  <el-menu
                    default-active="2"
                    class="el-menu-vertical-demo"
                    @open="handleOpen"
                    @close="handleClose">
                    <el-submenu index="1">
                      <template slot="title">
                        <i class="el-icon-location"></i>
                        <span>导航一</span>
                      </template>
                      <el-menu-item-group>
                        <template slot="title">分组一</template>
                        <el-menu-item index="1-1">选项1</el-menu-item>
                        <el-menu-item index="1-2">选项2</el-menu-item>
                      </el-menu-item-group>
                      <el-menu-item-group title="分组2">
                        <el-menu-item index="1-3">选项3</el-menu-item>
                      </el-menu-item-group>
                      <el-submenu index="1-4">
                        <template slot="title">选项4</template>
                        <el-menu-item index="1-4-1">选项1</el-menu-item>
                      </el-submenu>
                    </el-submenu>
                    <el-menu-item index="2">
                      <i class="el-icon-menu"></i>
                      <span slot="title">导航二</span>
                    </el-menu-item>
                    <el-menu-item index="3" disabled>
                      <i class="el-icon-document"></i>
                      <span slot="title">导航三</span>
                    </el-menu-item>
                    <el-menu-item index="4">
                      <i class="el-icon-setting"></i>
                      <span slot="title">导航四</span>
                    </el-menu-item>
                  </el-menu>
                </el-col>
              </el-row>
            </div>
            <!-- 知识图谱 -->
            <div class="test">
              <div v-if="!isGrade" class="graph common-shadow">
                <k-g-chart
                  ref="chart"
                  :entities="entities.entities"
                ></k-g-chart>
              </div>
            </div>
            <!-- 推荐资源 -->
            <div v-if="isGrade" class="boutique-resource common-shadow">
              <h2>精选资源</h2>
              <div class="list-container">
                <resource-list
                  :resourceList="boutiqueResources"
                  :browseTime="true"
                  :isHidden="true"
                ></resource-list>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import NavMenu from '@/components/NavMenu/'
import KnowledgeCard from '@/components/KnowledgeCard'
import ResourceLink from '@/components/ResourceLink'
import DownloadButton from '@/components/Buttons/DownloadButton'
import ResourceListWithInfo from '@/components/ResourceListWithInfo'
import GoalAndKeyCard from '@/components/GoalAndKeyCard'
import merge from 'webpack-merge'
import KGChart from '@/components/Chart/KGChart'
import History from '@/components/Chart/History'
import HistoryListShow from '@/components/Chart/HistoryListShow.vue'
import ResourceList from '@/components/ResourceList'
import PictureShow from '@/view/PictureShow/PictureShow'

import { record } from '@/api/record'
import { menus } from '@/api/menu'
// import { recommendByUserEntity } from '@/api/recommend'
// import { download } from '@/api/resource'
import { searchEntity, relatedEntity, entityIllustration } from '@/api/entity'
import { boutiqueResource } from '@/api/recommend'

import bus from '@/components/eventBus.js'
export default {
  name: 'ResourceCenter',
  components: {
    NavMenu,
    KGChart,
    KnowledgeCard,
    ResourceLink,
    DownloadButton,
    ResourceListWithInfo,
    GoalAndKeyCard,
    History,
    HistoryListShow,
    ResourceList,
    PictureShow
  },
  data() {
    return {
      imgs: [],
      searchInfo: {
        type: this.$route.query.type === undefined ? 0 : this.$route.query.type,
        content: this.$route.query.q,
        sort: this.$route.query.sort === undefined ? 0 : this.$route.query.sort,
        isClicked: this.$route.query.isClicked === undefined ? false : this.$route.query.isClicked,
        period: 0,
        subject: 0
      },
      pageInfo: {
        page: this.$route.query.page === undefined ? 1 : this.$route.query.page,
        perPage: 10
      },
      resourceTypes: [
        {
          label: '全部',
          code: 0
        },
        {
          label: '视频',
          code: 1
        },
        {
          label: '试题',
          code: 2
        },
        {
          label: '试卷',
          code: 3
        },
        {
          label: '课件',
          code: 4
        },
        {
          label: '文献资料',
          code: 5
        },
        {
          label: '教学案例',
          code: 6
        }
      ],
      resources: {
        resources: [],
        total: 0,
        pages: 0
      },
      noResourceHint: '',
      entities: {
        entities: []
      },
      cardInfo: {},
      goal: [],
      key: [],
      activeEntity: '',
      title: '',
      boutiqueResources: [],
      menus: [],
      // 当前学段学科列表
      curSubjects: [{ menuID: 0, menuName: '所有学科' }]
    }
  },
  computed: {
    query() {
      return this.$route.query
    },
    graphEntity() {
      return this.entities.entities
    },
    // 控制显示正常搜索页还是学段搜索页
    isGrade() {
      return this.checkIsGrade()
    },
    urlList() {
      return this.imgs.map(img => img.url)
    }
  },
  watch: {
    query: {
      handler(newQuery, oldQuery) {
        this.resetResource()
        this.searchInfo.type = newQuery.type === undefined ? '0' : newQuery.type
        this.searchInfo.sort = newQuery.sort === undefined ? 0 : newQuery.sort
        this.searchInfo.content = newQuery.q === undefined ? 0 : newQuery.q
        this.searchInfo.isClicked = newQuery.isClicked === undefined ? false : newQuery.isClicked
        this.searchInfo.period =
          this.$route.query.period === undefined
            ? 0
            : Number(this.$route.query.period)
        this.searchInfo.subject =
          this.$route.query.subject === undefined
            ? 0
            : Number(this.$route.query.subject)
        this.pageInfo.page = newQuery.page === undefined ? 1 : newQuery.page
        // console.log(this.searchInfo)

        this.goSearch()
        if (oldQuery === undefined || newQuery.q !== oldQuery.q) {
          this.resetCardInfo()
          this.resetEntity()
          this.resetGoalAndKey()
          if (newQuery.q !== '小学' && newQuery.q !== '初中' && newQuery.q !== '高中') {
            // this.getIllustration(newQuery.q)
            bus.$emit('share', newQuery.q)
          }
          this.getRelatedEntity(newQuery.q)
        }
        this.title = `${newQuery.q} - 智慧学伴`
      },
      immediate: true
    },
    graphEntity: {
      handler() {
        // this.$refs.chart.initCharts()
      }
    },
    title: {
      handler(title) {
        document.title = title
      },
      immediate: true
    },
    isGrade: {
      handler(isGrade) {
        if (isGrade) {
          this.getBoutique()
        }
      },
      immediate: true
    },
    menus: {
      handler() {
        if (this.isGrade) {
          const keyWords = ['小学', '初中', '高中']
          for (let i = 0; i < keyWords.length; i++) {
            if (this.searchInfo.content === keyWords[i]) {
              this.changePeriod(i + 2)
            }
          }
        }
        // 这一段放在这里就不会有学科 id 跳出来，只是会有所有学科这几个字跳出来，稍微正常一点
        // 但是放在这里会出现跳转之后请求出 bug
        // this.searchInfo.period =
        //   this.$route.query.period === undefined
        //     ? 0
        //     : Number(this.$route.query.period)
        // this.searchInfo.subject =
        //   this.$route.query.subject === undefined
        //     ? 0
        //     : Number(this.$route.query.subject)
      }
    }
  },
  created() {
    this.getMenus()
  },
  mounted() {},
  methods: {
    handleOpen(key, keyPath) {
      console.log(key, keyPath)
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath)
    },
    getIllustration(keywords) {
      this.imgs = []
      entityIllustration(keywords).then((response) => {
        this.imgs = response.data.data
      })
    },
    changeType(tab) {
      this.searchInfo.type = tab.name
      this.$router.push({
        query: merge(this.$route.query, {
          type: this.searchInfo.type,
          sort: 0,
          page: 1
        })
      })
    },
    goSearch() {
      this.noResourceHint = ''
      searchEntity({
        keyword: this.searchInfo.content,
        type: this.searchInfo.type,
        sort: this.searchInfo.sort,
        period: this.searchInfo.period,
        subject: this.searchInfo.subject,
        page: this.pageInfo.page,
        perPage: this.pageInfo.perPage,
        isClicked: this.searchInfo.isClicked
      }).then((response) => {
        this.resetResource()
        if (response.data.code === 200) {
          const resource = response.data.data.resources
          this.resources.total = response.data.data.total
          this.resources.pages = response.data.data.pages
          // 提取出教学目标和重难点以数组的形式存储
          const goal = []
          const key = []
          if (resource['goalAndKey']) {
            resource['goalAndKey'].forEach((goalAndKey) => {
              if (goalAndKey['objectives'] !== null) {
                goal.push({
                  content: goalAndKey['objectives'],
                  resourceID: goalAndKey['resourceID']
                })
              }
              if (goalAndKey['keyPoint'] !== null) {
                key.push({
                  content: goalAndKey['objectives'],
                  resourceID: goalAndKey['resourceID']
                })
              }
            })
            this.goal = goal
            this.key = key
          }

          // 找到和关键词一致的知识点
          if (resource.entityName === this.searchInfo.content) {
            this.cardInfo = resource.properties
          }
          this.resources.resources = resource
        }
        if (this.resources.resources.length === 0) {
          this.noResourceHint = '未查询到相关资源'
        }
      })
    },
    changeSort(sort) {
      this.$router.push({
        query: merge(this.$route.query, {
          type: this.searchInfo.type,
          page: 1,
          sort: sort
        })
      })
    },
    resetResource() {
      this.resources.resources = []
      this.resources.total = 0
      this.resources.pages = 0
    },
    resetGoalAndKey() {
      this.goal = []
      this.key = []
    },
    resetCardInfo() {
      this.cardInfo = {}
    },
    resetEntity() {
      this.entities.entities = []
    },
    getRelatedEntity(keyword) {
      this.resetEntity()
      relatedEntity(keyword).then((response) => {
        if (response.data.code === 200) {
          this.entities.entities = response.data.data
        }
      })
    },
    changePage(curPage) {
      this.$router.push({
        query: merge(this.$route.query, {
          page: curPage
        })
      })
    },
    viewResource(resourceID) {
      const target = this.$refs.resourceTarget
      record({
        resourceID: resourceID
      })
      target.setAttribute(
        'href',
        `${window.location.origin}/e-resource/#/resource/${resourceID}`
      )
      target.click()
    },
    //
    changeNode() {},
    checkIsGrade() {
      const keyWords = ['小学', '初中', '高中']
      for (let i = 0; i < keyWords.length; i++) {
        if (this.searchInfo.content === keyWords[i]) {
          return true
        }
      }
      return false
    },
    getBoutique() {
      boutiqueResource(this.searchInfo.content).then((response) => {
        const { code, data } = response.data
        if (code === 200) {
          this.boutiqueResources = data
        } else {
          this.$message.warning('服务器错误，请稍后刷新重试')
        }
      })
    },
    getMenus() {
      if (this.$store.state.menus.length === 0) {
        menus().then((response) => {
          const {
            data: { code, data }
          } = response
          if (code === 200) {
            this.menus = [
              { ID: 0, name: '所有学段' },
              ...data[0].classification
            ]
            this.$store.commit('initMenus', data)
          }
        })
      } else {
        this.menus = [
          { ID: 0, name: '所有学段' },
          ...this.$store.state.menus[0].classification
        ]
      }
    },
    changePeriod(id) {
      const subjects = this.menus.find((menu) => menu.ID === id).menu
      if (subjects) {
        this.curSubjects = [{ menuID: 0, menuName: '所有学科' }, ...subjects]
      } else {
        this.curSubjects = [{ menuID: 0, menuName: '所有学科' }]
      }
    },
    classificationSearch() {
      const curPeriod = Number(this.$route.query.period)
      const curSubject = Number(this.$route.query.subject)
      if (
        curPeriod !== this.searchInfo.period ||
        curSubject !== this.searchInfo.subject
      ) {
        this.$router.push({
          query: merge(this.$route.query, {
            period: this.searchInfo.period,
            subject: this.searchInfo.subject,
            page: 1
          })
        })
      }
    }
  }
}
</script>

<style scoped>

.imgs-container{
  display: flex;
  align-items: center;
  width: 900px;
  height: 200px;
  margin: 2rem;
  overflow-x: auto;
}
.img-item {
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  margin-right: 15px;
  /*很重要，禁止子元素的收缩*/
  flex-shrink: 0;
}
.lg-container {
  background-color: #f7f5f4;
  min-height: calc(100vh - 130px);
  padding-bottom: 2rem;
}

.sort {
  margin-top: -0.5rem;
  margin-bottom: 0.5rem;
}

.resources {
  display: flex;
  /*justify-content: space-evenly;*/
}

.entity-title {
  font-size: 1.2rem;
  line-height: 1.2rem;
}

.resource-list {
  border-top: 1px solid #dcdfe6;
}

.resource .subtitle {
  color: #606266;
}

.content-link {
  overflow: hidden;
  position: relative;
  cursor: pointer;
  text-align: justify;
  width: 100%;
  font-size: 0.8rem;
  line-height: 1.2rem;
  height: 1.2rem;
  color: #909399;
}

.content-link:hover {
  color: #53a8ff;
  text-decoration: underline;
  text-underline-offset: 0.2rem;
}

/*省略号*/
.overflow-content::after {
  content: '...';
  position: absolute;
  bottom: 0;
  right: 0;
  /*将省略号的大小设置为1个字体大小*/
  width: 1em;
  /*设置背景，将最后一个字覆盖掉*/
  background: #fff;
}

.resource-content-container {
  background-color: #fff;
  margin-top: 1rem;
  padding: 0.5rem 1.2rem 1.2rem;
}

.resource {
  margin-bottom: 1rem;
}

.knowledge-card {
  margin-top: 1rem;
  box-shadow: 1px 3px 6px rgb(122 122 122 / 0.2);
}

.entity:first-child {
  margin-left: -2px;
}

.pages {
  display: flex;
  justify-content: center;
  padding-bottom: 2rem;
}

.graph {
  float: right;
  padding-left: 1rem;
  padding-right: 1rem;
  margin-top: 1rem;
  margin-left: 1rem;
  width: 1000px;
  height: 420px;
  min-height: 400px;
  background-color: white;
}

.boutique-resource {
  padding: 1rem 1rem 0.5rem;
  width: 400px;
  margin-top: 1rem;
  margin-left: 1rem;
  background-color: white;
}

.boutique-resource h2 {
  padding-bottom: 8px;
  margin-bottom: 1rem;
  border-bottom: solid 1px #a5a3a3;
}

.history-container {
  padding: 0.5rem 1rem;
  margin-top: 1rem;
  margin-left: 1rem;
  width: 400px;
  background-color: white;
}

.graph button {
  margin-top: 10px;
}

/*教学目标和教学重难点卡片*/
.goal-and-key-container {
  justify-content: space-between;
}

.goal-and-key-card {
  width: calc(50% - 10px);
  height: 190px;
}

/* 分类搜索 */
.search-tab {
  display: flex;
  align-items: center;
  margin: 0.5rem 0;
}

.search-tab .subtitle {
  font-weight: bold;
  margin-right: 1rem;
}

.classification-select {
  width: 120px;
  margin-right: 1rem;
}

/* ***** */
</style>
